import React from 'react'
import {ProductModel} from '../api/product'
import {KindModel} from '../api/kind'
import {
  message, Table, Divider,
  Button, Modal, Input, Select,
  Upload, Icon
} from "antd";
import '../style/product.less'

const { confirm } = Modal;
const { TextArea } = Input;

const productModel=new ProductModel()
const kindModel=new KindModel()

class Product extends React.Component{
  constructor(props) {
    super(props);
    this.state={
      list:[],
      kind_list:[],
      visible:false,
      ifEdit:false,
      id:0,
      modelTitle:'编辑产品',
      nameValue:'',
      kindIdValue:'',
      desValue:'',
      imageUrl:'',
      fileName:''
    }
    this.getList()
  }

  getList(){
    kindModel.getList()
      .then(res=>{
        if(res.code===0){
          this.setState({
            kind_list:res.data
          })

          productModel.getList().then(resd=>{
            console.log(resd);
            if(resd.code===0){

              this.setState({
                list:resd.data
              })
            }

          }).catch(error=>{
            console.log(error);
            message.error('获取列表失败')
          })
        }
      })
      .catch(err=>{
        console.log(err);
      })
  }

  openCreateModel(){
    this.setState({
      ifEdit:false,
      visible:true,
      modelTitle:'新建产品',
      id:0,
      nameValue:'',
      kindIdValue:'',
      desValue:''
    })
  }

  handleUploadChange(info) {
    console.log(info);
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      // console.log(info.file.response.file);
      getBase64(info.file.originFileObj, imageUrl =>{
        this.setState({
          imageUrl,
          loading: false,
          fileName:info.file.response.data.fileName
        })
      });
    }
  };

  changeKindValue(value){
    this.setState({
      kindIdValue:value
    })
  }
  handleCancel(){
    this.setState({
      visible:false
    })
  }

  handleOk(){
    const {id,nameValue,kindIdValue,desValue,fileName}=this.state
    if(this.state.ifEdit){
      this.updateObject(id,nameValue,kindIdValue,desValue,fileName)
    }else{
      this.createObject(nameValue,kindIdValue,desValue,fileName)
    }
  }

  createObject(name,kind_id,description,fileName){
    productModel.createProduct(name,kind_id,description,fileName).then(res=>{
      if(res.code===0){
        message.success("创建成功")
        this.getList()
        this.setState({
          visible:false,
          imageUrl:null
        })
      }

    }).catch(error=>{
      message.error(error.toString())
    })
  }
  changeNameValue(e){
    this.setState({
      nameValue:e.target.value
    })
  }
  changeDesValue(e){
    this.setState({
      desValue:e.target.value
    })
  }

  openDeleteModel(record){
    const _this=this
    confirm({
      title: '删除产品',
      content: '是否确定删除此产品',
      onOk() {
        productModel.deleteProduct(record._id).then(res=>{
          if(res.code===0){
            message.success("删除成功")
            _this.getList()
          }else{
            message.success(res.msg)
          }
        }).catch(error=>{
          message.error(error)
        })
      },
      onCancel() {},
    })
  }

  openUpdateModel(record){
    this.setState({
      ifEdit:true,
      visible:true,
      modelTitle:'编辑产品',
      id:record._id,
      nameValue:record.name,
      kindIdValue:record.kind_id,
      desValue:record.des
    })
  }

  updateObject(id,name,kind_id,description,fileName){
    productModel.editProduct(id,name,kind_id,description,fileName).then(res=>{
      if(res.code===0){
        message.success("修改成功")
        this.getList()
        this.setState({
          visible:false,
          imageUrl:null
        })
      }

    }).catch(error=>{
      message.error(error)
    })
  }

  render() {
    const { imageUrl } = this.state;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const columns=[
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '图片',
        dataIndex: 'pic',
        key: 'pic',
        render:(text,record)=>(
          <span>
            <img width={200} src={productModel.getImageAddress(record.pic)}/>
          </span>
        )
      },{
        title: '所属分类',
        dataIndex: 'kind_id',
        key: 'kind_name',
        render:(text,record)=>(
          <span>{this.state.kind_list.filter(v=>v._id===text)[0]?this.state.kind_list.filter(v=>v._id===text)[0]["name"]:null}</span>

        )
      },{
        title: '描述',
        dataIndex: 'des',
        key: 'description',
      },{
        title: '操作',
        key: 'action',
        render:(text, record)=>(
          <span>
            <Button type="link" onClick={()=>this.openUpdateModel(record)} >编辑</Button>
            <Divider type="vertical" />
            <Button type="link" onClick={()=>this.openDeleteModel(record)}>删除</Button>
          </span>
        )
      }
    ]
    return (
      <div>
        <Button onClick={()=>this.openCreateModel()} type="primary">添加</Button>
        <br/><br/>
        <Table
          rowKey={record=>record._id}
          dataSource={this.state.list}
          columns={columns} />

        <Modal
          title={this.state.modelTitle}
          visible={this.state.visible}
          onOk={()=>this.handleOk()}
          onCancel={()=>this.handleCancel()}
        >

          <Select value={this.state.kindIdValue}  className="select-style" onChange={(event)=>this.changeKindValue(event)}>
            {
              this.state.kind_list.map(item=>{
                return (
                  <Select.Option key={item._id}  value={item._id}>{item.name}</Select.Option>
                )
              })
            }

          </Select>
          <br/><br/>
          <div>
            <Upload
              name="pic"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={productModel.getUploadAddress()}
              beforeUpload={beforeUpload}
              onChange={(info)=>this.handleUploadChange(info)}
            >
              {imageUrl ? <img className="img-style" src={imageUrl} alt="avatar" /> : uploadButton}
            </Upload>
          </div>
          <Input
            placeholder="名称"
            value={this.state.nameValue}
            onChange={(event)=>this.changeNameValue(event)}
          />
          <br/><br/>
          <TextArea
            rows={4}
            value={this.state.desValue}
            onChange={(event)=>this.changeDesValue(event)}
          />

        </Modal>
      </div>
    );
  }
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const fileTypes=['image/jpeg','image/jpg','image/png']

  const isJPG = fileTypes.indexOf(file.type) !== -1;
  if (!isJPG) {
    message.error('You can only upload JPG or PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJPG && isLt2M;
}

export default Product;
